package logic

import (
	"errors"
	"gorm.io/gorm"
	"iot-base/auth/model"
	"iot-base/auth/svc"
	types2 "iot-base/auth/types"
)

type PresetLogic struct {
}

func NewPresetLogic() *PresetLogic {
	return &PresetLogic{}
}

func (l *PresetLogic) GetPresets(thingId string) ([]model.Presets, error) {
	return svc.Dao.TPresets.GetPresetFinds(thingId)
}

func (l *PresetLogic) SetPreset(data types2.ReqSetPreset) error {
	_, err := svc.Dao.TPresets.FindPreset(data.ThingId, data.PresetToken)
	insetData := model.Presets{
		PresetToken: data.PresetToken,
		PresetName:  data.PresetName,
		ThingId:     data.ThingId,
	}
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return svc.Dao.TPresets.AddPreset(&insetData)
	}
	if err != nil {
		return err
	}
	_, err = svc.Dao.TPresets.UpdatePreset(&insetData)
	return err
}

func (l *PresetLogic) RemovePreset(data types2.ReqSetPreset) (int64, error) {
	return svc.Dao.TPresets.DelPreset(data.ThingId, data.PresetToken)
}
